package net.hackbard.piratenradio;

import java.io.IOException;

import com.pocketjourney.media.StreamingMediaPlayer;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;

public class PlayerService extends Service {

	private StreamingMediaPlayer audioStreamer;
	private TelephonyManager m_telephonyManager;
	private final IBinder mBinder = new LocalBinder();

	public class LocalBinder extends Binder {
		PlayerService getService() {
			return PlayerService.this;
		}
	}

	@Override
	public void onCreate() {
		registerReceiver(new BroadcastsHandler(), new IntentFilter(
				AudioManager.ACTION_AUDIO_BECOMING_NOISY));
		m_telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		m_telephonyManager.listen(new MyPhoneStateListener(),
				PhoneStateListener.LISTEN_CALL_STATE);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	public void startStreamingAudio(TextView textStreamed, String streamUrl) {
		try {
			if (audioStreamer != null) {
				audioStreamer.interrupt();
			}
			audioStreamer = new StreamingMediaPlayer(this, textStreamed);
			audioStreamer.startStreaming(streamUrl, 5208, 216);			
		} catch (IOException e) {
			Log.e(getClass().getName(), "Error starting to stream audio.", e);
		}
	}
	public void pauseStreamingAudio() {
		if (audioStreamer != null) {
			if (audioStreamer.getMediaPlayer().isPlaying()) {
				audioStreamer.getMediaPlayer().pause();
			}
		}
	}
	public void stopStreamingAudio() {
		if (audioStreamer != null) {
			audioStreamer.interrupt();
		}
		audioStreamer.interrupt();
		audioStreamer = null;
	}

	class MyPhoneStateListener extends PhoneStateListener {
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				stopStreamingAudio();
				break;
			default:
				break;
			}
		}
	}

	public class BroadcastsHandler extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String intentAction = intent.getAction();
			if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intentAction)) {
				stopStreamingAudio();
			}
		}
	}
}
